package com.yida.controller;

import com.yida.bean.blogUser;
import com.yida.service.serverLogin;
import com.yida.util.QQHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.URLEncoder;
import java.util.UUID;

@Controller
public class qqLogin {
	
	@Autowired
	serverLogin serverLogin;

   //QQ互联中的回调地址	
   String backUrl = "https://taoyida.top/connect";
	
   //gg55566
   
	@RequestMapping("/login")
	public String login(HttpServletRequest request) {

//		 // 获取完整的请求路径，包括：域名，端口，上下文访问路径
//			String domain=getDomain(request);
//			String scheme = request.getHeader("X-Forwarded-Scheme");
//			String replace=domain.replace("http",scheme);
//
//		System.out.print(replace);

		return "login";
	}

//	public  String  getDomain(HttpServletRequest request){
//		StringBuffer url = request.getRequestURL();
//		String contexPath = request.getServletContext().getContextPath();
//		return  url.delete(url.length() - request.getRequestURI().length(),url.length()).append(contexPath).toString();
//	}
	
	
	  @RequestMapping("/qqLogin")
	    public String qqLogin(HttpServletRequest request, HttpServletResponse response)throws Exception{
		  
	        //用于第三方应用防止CSRF攻击	
	        String uuid = UUID.randomUUID().toString().replaceAll("-","");	
	        request.getSession().setAttribute("state",uuid);	
	 	
	        //Step1：获取Authorization Code	
	        String url = "https://graph.qq.com/oauth2.0/authorize?response_type=code"+	
	                "&client_id=" + QQHttpClient.APPID +	
	                "&redirect_uri=" + URLEncoder.encode(backUrl) +	
	                "&state=" + uuid;	
	 	
	        return "redirect:" + url;
	    }
	  
	  
	  @RequestMapping("/connect")
	    public String connect(HttpServletRequest request, HttpServletResponse response,Model mode)throws Exception{
		  
		  HttpSession session = request.getSession();	
	        //qq返回的信息：http://graph.qq.com/demo/index.jsp?code=9A5F************************06AF&state=test	
	        String code = request.getParameter("code");	
	        String state = request.getParameter("state");	
	        String uuid = (String) session.getAttribute("state");	
	 	
	        if(uuid != null){	
	            if(!uuid.equals(state)){	
	                throw new Exception("QQ,state错误");	
	            }	
	        }	

	        String url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code"+	
	                "&client_id=" + QQHttpClient.APPID +	
	                "&client_secret=" + QQHttpClient.APPKEY +	
	                "&code=" + code +	
	                "&redirect_uri=" + backUrl;	
	 	
	        String access_token = QQHttpClient.getAccessToken(url);	
	        
	      
	 	    
	        //Step3: 获取回调后的 openid 值	
	        url = "https://graph.qq.com/oauth2.0/me?access_token=" + access_token;	
	        String openid = QQHttpClient.getOpenID(url);	
	 	
	        //Step4：获取QQ用户信息	
	        url = "https://graph.qq.com/user/get_user_info?access_token=" + access_token +	
	                "&oauth_consumer_key="+ QQHttpClient.APPID +	
	                "&openid=" + openid;	
	 	
	        com.alibaba.fastjson.JSONObject jsonObject = QQHttpClient.getUserInfo(url);	
	 	
	        String nickname = (String)jsonObject.get("nickname");
	        String imgUrl = (String)jsonObject.get("figureurl_qq_2");
	        String sex = (String)jsonObject.get("gender");
	      
	       //也可以放到Redis和mysql中	
	       // session.setAttribute("openid",openid);  //openid,用来唯一标识qq用户	
	       // session.setAttribute("nickname",(String)jsonObject.get("nickname")); //QQ名	
	       // session.setAttribute("figureurl_qq_2",(String)jsonObject.get("figureurl_qq_2")); //大小为100*100像素的QQ头像URL	
	 	   
	        Integer id = serverLogin.ThirdByUnique(openid);
	       
	        
	      if (id==null) {
	    	   blogUser result = serverLogin.insertThirdUserAndUser(openid, "1", nickname, sex, imgUrl);
	    	 if (result!=null) {
	    		 session.setAttribute("user", result);
	    		 session.setAttribute("openid", openid);
	    		  return "redirect:/";
			} else {
				
				  return "redirect:/login";
			}
	    	  
		 }else {
			blogUser user = serverLogin.blogUserByOpenId(openid);
			session.setAttribute("user", user);
			session.setAttribute("openid", openid);
			 return "redirect:/";
		}
	         
	    }

	
	  @RequestMapping("/qqLoginOut")
	  public String qqLoginOut(HttpServletRequest request) {
		  request.getSession().removeAttribute("user");

		return "redirect:/";
		
	}
	  
}
